package cn.cjxy.controller;

import cn.cjxy.domain.User;
import cn.cjxy.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
//Restful风格请求
@RestController//相当于 @Controller+@ResponseBody
@RequestMapping("/user")
public class UserControllerRestful {

    //注入mapper对象
    @Autowired
    private UserMapper userMapper;
    /**
     * 查询所有   http://localhost:8080/user
     * 查询单个   http://localhost:8080/user/id
     * 删除：     http://localhost:8080/user/id
     * 新增：     http://localhost:8080/user
     * 修改：     //http://localhost:8080/user
     */
    /**
     * get方式请求查询所有--不带参      //http://localhost:8080/user
     * @return
     */
    @GetMapping
    public List<User> findAll() {
        //调用mapper层方法
        List<User> all = userMapper.findAll();
        return all;
    }

    /**
     * get方式查询用户---带参（地址参数）
     * @param id
     * @return
     */
    @GetMapping("/{id}")//http://localhost:8080/user/id
    public User findById(@PathVariable Integer id) {
        return userMapper.findById(id);
    }

    /**
     * delete方式请求-删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}") //http://localhost:8080/user/id
    public String deleteById(@PathVariable Integer id) {
        boolean b = userMapper.deleteById(id);
        if (b){
            return "删除成功！";
        }
        return "删除失败";
    }

    /**
     * 新增用户--post方式请求
     * @param user
     */
    @PostMapping//http://localhost:8080/user
    public void save(@RequestBody User user) {
        userMapper.insert(user);
    }

    /**
     * 修改用户--put方式请求
     * @param user
     */
    @PutMapping//http://localhost:8080/user
    public void update(@RequestBody User user) {
        userMapper.updateUser(user);
    }
}
